/**
 * Created by huangzuizui on 2018/4/14.
 */
'use strict';
import React, { Component } from 'react';
import { axiosInstance } from '../../app.config';
import style from './Dictionary.scss';
import readWord from '../readWord.web';
import qs from 'qs';
import { host } from '../../config';
import authentication from '../HOC/authentication';

const cacheWords = {};

const addToNoteBook = function (wordData) {
  return new Promise((resolve, reject) => {
    ((factory) => {
      if (!window.zzeng.videoId) {
        axiosInstance.get('/UserVIdeo/getId', {
          params: {
            videoHash: window.zzeng.fileHash,
            subtitleHash: window.zzeng.subtitleHash,
            title: window.zzeng.fileName,
          },
        }).then((res) => {
          // 如果是新创建的,同时把字幕也更新掉
          if (res.data.data.new) {
            axiosInstance.post('/UserVideo/UploadSubtitle', qs.stringify({
              id: res.data.data.id,
              subtitle: JSON.stringify(window.zzeng.subtitle),
            }))
          }
          window.zzeng.videoId = res.data.data.id;
          factory(window.zzeng.videoId);
        })
        return;
      }
      factory(window.zzeng.videoId);
    })((userVideoId) => {
      axiosInstance.post('/Word/add', {
        ...wordData,
        userVideoId,
        sourceType: 'VIDEO',
      }).then(resolve, reject);
    })
  })
}

class Dictionary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
    }
    this.hideDictionary = this.hideDictionary.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.word !== this.props.word) {
      const { dict, word: searchWord } = nextProps.word;
      this.setState({
        searchWord,
        word: dict.word || dict.relatedWords[0],
        originWord: dict.word || dict.relatedWords[0],
        relatedWords: dict.relatedWords,
      });
    }
  }

  componentWillUpdate(nextProps, nextState) {
    return nextState !== this.state;
  }

  componentDidMount() {
     window.addEventListener('click', this.hideDictionary);

    axiosInstance.get(`/Dict?json=1&word=${this.props.selection.text}`).then((res) => {
      const { dict, word: searchWord } = res.data.data;
      if (dict) {
        this.setState({
          searchWord,
          word: dict.word || dict.relatedWords[0],
          originWord: dict.word || dict.relatedWords[0],
          relatedWords: dict.relatedWords,
          loading: false,
        })
      } else {
        this.setState({
          searchWord,
          loading: false,
        });
      }
    });
  }

  componentWillUnmount() {
    window.removeEventListener('click', this.hideDictionary);
  }

  hideDictionary(e) {
    const loginModal = this.props.getLoginModal();
    const loginState = loginModal ? !loginModal.contains(e.target) : true;
    if (this.refs.dictionary && !this.refs.dictionary.contains(e.target) && loginState) {
      this.props.clearSelection();
    }
  }

  setWord(word) {
    this.setState({
      word,
    })
  }

  handleAddWord() {
    this.props.checkLogin().then((resss) => {
      console.log('resss', resss);
      const wordData = {
        did: this.state.word.id,
        originWord: this.props.selection.text,
        word: this.state.word.word,
        sentence: this.props.selection.sentence,
      };

      addToNoteBook(wordData).then((res) => {
        console.log('word ===add:', res);
         this.props.clearSelection();
      });
    })
  }

  render() {
    if (this.state.loading) return <div className={`${style.dictionary} ${style.loading}`} />;
    if (!this.state.word) {
      return (
        <div ref="dictionary" className={style.dictionary}>
          <span>未找到"{this.state.searchWord}"相关结果</span>
        </div>
      );
    }

    const { word, relatedWords, originWord } = this.state;
    console.log('originWord', originWord);

    const phoneticEN = word.prons.match(/\[英\]\[[\w\W]+?\]/);
    const phoneticUS = word.prons.match(/\[美\]\[[\w\W]+?\]/);
    return (
      <div ref="dictionary" className={style.dictionary}>
        <div className={style.header}>
          {!!word && (
            <div>
              <span className={style.b}>{word.word}</span>
              <span className={style.addButton} onClick={this.handleAddWord.bind(this)}>
                <span className="iconfont icon-add" />
              </span>
            </div>
          )}
          {!word && <span>没有找到"{this.props.word.word}"结果。</span>}
          {!!this.props.addedWordsNumber && (
            <span className={style.notebook + ' iconfont icon-bijiben-copy'}>
              <span>{this.props.addedWordsNumber}</span>
            </span>
          )}
        </div>
        <div className={style.content}>
          <div onClick={this.setWord.bind(this, originWord)} className={style.originWord}>{originWord.word}</div>
          {!!relatedWords.length && (
            <div>
              <span>相关结果:</span>
              {relatedWords.map((w, index) => (
                <span className={style.relatedWord} key={index} onClick={this.setWord.bind(this, w)}>
                  {w.word}
                </span>
              ))}
            </div>
          )}
          <div>
            {(phoneticUS || phoneticEN) && (
              <div>
                <div className={style.phonetics}>
                  {phoneticUS && (
                    <div onClick={readWord.bind(this, word.word, 'us')} className={style.phonetic}>
                      <span className="iconfont icon-laba" /> <span>{phoneticUS}</span>
                    </div>
                  )}
                  {phoneticEN && (
                    <div onClick={readWord.bind(this, word.word, 'en')} className={style.phonetic}>
                      <span className="iconfont icon-laba" /> <span>{phoneticEN}</span>
                    </div>
                  )}
                </div>
              </div>
            )}
            <div>
              <div className={style.sectionHeader}><span>词义</span></div>
              <div dangerouslySetInnerHTML={{__html:word.meaning}}/>
            </div>
            <div>
              <div className={style.sectionHeader}><span>例句</span></div>
              <div dangerouslySetInnerHTML={{__html:word.centence}}/>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default authentication(Dictionary);
